package com.LockCondition;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 假设做一个缓存数据库，读写锁并用，可以多线程调用且高性能不出问题
 */
public class CacheDemo_lock {
    //声明下自己的缓存数据库
    private Map<String,Object> cache=new HashMap<>();
    public static  void main(String[] org0){
       CacheDemo_lock cacheDemo_lock=new CacheDemo_lock();
        System.out.println( cacheDemo_lock.getData("zhangkai"));
    }
    private ReadWriteLock rw1=new ReentrantReadWriteLock();//创建锁
    public Object getData(String key)
    {

        rw1.readLock().lock();//=================加上读锁
        Object value=null;
        try {
            value = cache.get(key);//============获取缓存数据的数据
            if (value==null){    //==============如果缓存数据为空
                rw1.readLock().unlock();//=======放开读锁
                rw1.writeLock().lock();//========加上写锁
                try {
                    if (value==null){ //=========防止大家都读都为空然后都等着第一个线程去修改
                         value = "查询数据库并放到缓存区";
                    }
                }finally {
                    rw1.writeLock().unlock();//===解开写锁
                }
                rw1.readLock().lock();//==========把读锁再加上
            }
        }
        finally {
            rw1.readLock().unlock(); //==========解开读锁
        }
        return value;
    }

}
